import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/home/notes/home_card_view.dart';
import 'package:flutter_douban/main_page/home/notes/note_detail_centerView.dart';
import 'package:flutter_douban/main_page/home/notes/note_detail_footer.dart';
import 'package:flutter_douban/main_page/home/notes/note_detail_header.dart';
import 'package:flutter_douban/main_page/home/video/video_page.dart';
import 'package:flutter_douban/model/active_big_model.dart';
import 'package:flutter_douban/model/note_model.dart';
import 'package:flutter_douban/tool_views/loading_page.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_douban/main.dart';

class WindowVideoPage extends StatefulWidget {
  PlayType playType;
  String? dataSource;
  final int id;
  //UI
  bool showBottomWidget;
  bool showClearBtn;

  WindowVideoPage(
      {this.showBottomWidget = true,
      this.showClearBtn = true,
      this.dataSource,
      this.playType = PlayType.network,
      required this.id});

  @override
  _WindowVideoPageState createState() => _WindowVideoPageState();
}

class _WindowVideoPageState extends State<WindowVideoPage> {
  late EasyRefreshController _easyRefreshController;
  // late TencentPlayerController? controller;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;
  late VoidCallback? listener;
  DeviceOrientation? deviceOrientation;
  bool isLock = false;
  bool showCover = false;
  Timer? timer;
  late NoteModel _model;

  /// 列表数组模型
  List<ActiveBigModel> _relatedList = ActiveBigModelList([]).list;

  _WindowVideoPageState() {
    listener = () {
      if (!mounted) {
        return;
      }
      setState(() {});
    };
  }

  /// 获取详情内容
  Future _getNotesContentData() async {
    try {
      /// 全部数据
      Map<String, dynamic> result =
          await HttpService.getNotesContentData(id: widget.id);

      /// 列表
      NoteModel model = NoteModel.fromJson(result['note']);
      setState(() {
        _model = model;
        _getRelatedNotesData();
      });
    } catch (e) {
      setState(() {});
    } finally {
      setState(() {});
    }
  }

  /// 获取相关笔记数据
  Future _getRelatedNotesData({bool replace = true}) async {
    try {
      /// 全部数据
      Map<String, dynamic> result = await HttpService.getNotesDetailData(
          page: 1, pageSize: 10, id: widget.id);

      /// 列表
      ActiveBigModelList activeBigModelList =
          ActiveBigModelList.fromJson(result['list']);
      setState(() {
        if (replace) {
          _relatedList = activeBigModelList.list;
        } else {}
      });
    } catch (e) {
      setState(() {});
    } finally {
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();

    /// 隐藏状态栏
    _easyRefreshController = EasyRefreshController();
    _getNotesContentData();
  }

  @override
  void dispose() {
    super.dispose();

    /// 页面消失显示状态栏
    _easyRefreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {},
          onDoubleTap: () {},
          child: (_relatedList.length > 0)
              ? NotificationListener(
                  onNotification: (scrollNotification) {
                    if (scrollNotification is ScrollUpdateNotification &&
                        scrollNotification.depth == 0) {
                      /// 视频滑动出可视范围暂停视频
                      if (scrollNotification.metrics.pixels >=
                          int.parse(_model.video_cover_height!) *
                              MediaQuery.of(context).size.width /
                              int.parse(_model.video_cover_width!)) {
                        // controller!.pause();
                      } else {
                        // controller!.play();
                      }
                    }
                    return true;
                  },
                  child: Container(
                    color: Colors.white,
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height,
                    child: Stack(
                      children: [
                        Container(
                            padding: EdgeInsets.only(
                              top: kToolbarHeight + 8,
                              bottom: kToolbarHeight,
                            ),
                            child: EasyRefresh(
                              firstRefresh: false,
                              firstRefreshWidget: LoadingPage(),
                              header: CustomHeaderView(),
                              footer: CustomFooterView(),
                              controller: _easyRefreshController,
                              enableControlFinishRefresh: false,
                              enableControlFinishLoad: true,
                              child: Column(
                                children: [
                                  _videoWidget(),
                                  NoteCenterView(
                                    model: _model,
                                  ),
                                  Container(
                                    padding:
                                        EdgeInsets.only(left: 15, right: 15),
                                    color: Colors.white,
                                    width: MediaQuery.of(context).size.width,
                                    child: Text(
                                      '相关笔记',
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 18,
                                          color: Colors.black),
                                    ),
                                  ),
                                  _gradWidget(),
                                ],
                              ),
                            )),
                        Positioned(
                          top: 0,
                          child: NoteDetailHeader(
                            model: _model,
                          ),
                        ),
                        Positioned(
                          bottom: 0,
                          child: SafeArea(
                            child: NoteDetailFooter(model: _model),
                          ),
                        )
                      ],
                    ),
                  ),
                )
              : StancePage()),
    );
  }

  Widget _videoWidget() {
    return VideoPage(
      video_url: _model.video_url!,
      video_cover_height: _model.video_cover_height!,
      video_cover_width: _model.video_cover_width!,
    );
  }

  /// 瀑布流
  Widget _gradWidget() {
    return Container(
      padding: EdgeInsets.only(
        left: 5,
        right: 5,
      ),
      color: Colors.white,
      child: StaggeredGridView.countBuilder(
        controller: _scrollController,
        itemCount: _relatedList.length,
        primary: false,
        shrinkWrap: true,
        crossAxisCount: 4,
        mainAxisSpacing: 10.0,
        crossAxisSpacing: 5.0,
        itemBuilder: (context, index) => ActiveCardView(
          model: _relatedList[index],
        ),
        staggeredTileBuilder: (index) => StaggeredTile.fit(2),
      ),
    );
  }
}
